#include "snake.h"
#include<iostream>
#include<vector>
#include<graphics.h>
#include<conio.h>
#include<windows.h>
using namespace std;
COLORREF lerpColor(COLORREF c1, COLORREF c2, float t) {
	int r = GetRValue(c1) + (GetRValue(c2) - GetRValue(c1)) * t;
	int g = GetGValue(c1) + (GetGValue(c2) - GetGValue(c1)) * t;
	int b = GetBValue(c1) + (GetBValue(c2) - GetBValue(c1)) * t;
	return RGB(r, g, b);
}
void snake::Init()
{
	body.push_back({ 12, 8});
	direction = { 0,0 };
	isgrow = 0;
}
void snake::grow()
{
	isgrow = 1;
}
void snake::move(vector<point>&f)
{
	point newHead = { body.front().x + direction.x,body.front().y + direction.y };
	body.insert(body.begin(), newHead);
	for (auto seg:f)
	{
		if (newHead.x==seg.x&&newHead.y==seg.y)
		{
			snake::grow();
		}
	}
	if (!isgrow)
	{
		body.pop_back();
	}
	else
	{
		isgrow = 0;
	}
}
point snake::getHead()
{
	return body.front();
}
bool snake::checkPz()
{
	point head = snake::getHead();
	if (head.x <= 0 || head.x >= 24|| 2*head.y < 3 || head.y >= 16)
	{
		return 1;
	}
	for (size_t i = 1; i < body.size(); i++)
	{
		if (head.x == body[i].x && head.y == body[i].y) 
		{
			return 1;
		}
	}
	return 0;
}
void snake::draw()
{
	int n = body.size();
	COLORREF headColor = RGB(0, 200, 255);
	COLORREF tailColor = RGB(0, 40, 100);

	for (int i = 0; i < n; ++i) {
		float t = n == 1 ? 0 : (float)i / (n - 1);
		COLORREF color = lerpColor(headColor, tailColor, t);
		setfillcolor(color);
		const point& segment = body[i];
		solidrectangle(segment.x * 40, segment.y * 40, (segment.x + 1) * 40, (segment.y + 1) * 40);
	}
}
void snake::setDirection(int dx, int dy)
{
	if (dx!=-direction.x||dy!=-direction.y)
	{
		direction = { dx,dy };
	}
}